/**
 * 
 */
package com.jolestar.yayaweibotong.controller;

import java.io.IOException;
import java.util.logging.Logger;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author jolestar@gmail.com
 * 
 */
public abstract class AbstractAction implements WebAction {

	protected Logger log = Logger.getLogger(this.getClass().getName());
	protected String name;

	public AbstractAction(String name) {
		this.name = name;
	}

	public String getName() {
		return name;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.jolestar.yayaweibotong.controller.WebAction#doAction(javax.servlet
	 * .http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	@Override
	public void action(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String view = this.doAction(request, response);
		if (view == null) {
			return;
		} else if (view.startsWith("redirect:")) {
			this.redirect(request, response,
					view.substring(view.indexOf(':') + 1));
		} else if (view.startsWith("error:")) {
			this.error(request, response,
					Integer.parseInt(view.substring(view.indexOf(':') + 1)));
		} else {
			this.dispatch(request, response, view);
		}
	}

	protected abstract String doAction(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException;

	protected void dispatch(HttpServletRequest request,
			HttpServletResponse response, String view) throws ServletException,
			IOException {
		RequestDispatcher dispatcher = request
				.getRequestDispatcher("/WEB-INF/jsp/" + view + ".jsp");
		dispatcher.forward(request, response);
	}

	protected void redirect(HttpServletRequest request,
			HttpServletResponse response, String view) throws ServletException,
			IOException {
		response.sendRedirect(view);
	}

	protected void error(HttpServletRequest request,
			HttpServletResponse response, int code) throws ServletException,
			IOException {
		response.sendError(code);
	}
}
